﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework.Input.Touch;
using System.ComponentModel;

namespace TM.QWeibo.Client.UserControls
{
    public class RichTweetBox : RichTextBox 
    {


        #region 自定义属性
        /// <summary>
        /// 依赖项，显示的时间线内容类型
        /// </summary>
        public static DependencyProperty OrigTextProperty = DependencyProperty.Register("OrigText",
            typeof(string),
            typeof(RichTweetBox),
            new PropertyMetadata(""));

        /// <summary>
        /// 微博的原始内容
        /// </summary>
        [Description("微博的原始内容")]
        public string Origtext
        {
            get { 
                return this.GetValue(OrigTextProperty).ToString(); 
            }
            set { 
                this.SetValue(OrigTextProperty, value); 
            }
        }
        #endregion


        //public override void OnApplyTemplate()
        //{
        //    base.OnApplyTemplate();
        //    var tag = this.Tag;
        //    SetContent(tag+"");
        //}


        ///// <summary>
        ///// 设置内容
        ///// </summary>
        //public void SetContent(string text)
        //{
        //    try
        //    {
        //        if (string.IsNullOrEmpty(text)) return;

        //        var contentHelper = new Helper.TweetHelper(text);

        //        this.Blocks.Clear();

        //        if (contentHelper.Urls.Count > 0)
        //        {
        //            var urls = contentHelper.Urls.ToArray();
        //            for (int i = 0; i < urls.Length; i++)
        //            {
        //                var url = urls[i];
        //                var index = text.IndexOf(url);
        //                var startStr = text.Substring(0, index);
        //                PaserFace(startStr);
        //                var link = new Hyperlink();
        //                link.Foreground = new SolidColorBrush(Color.FromArgb(255, 82, 166, 239));
        //                link.NavigateUri = new Uri(url, UriKind.Absolute);
        //                link.Inlines.Add(url);
        //                link.Click += LinkTask;
        //                this.Selection.Insert(link);
        //                text = text.Substring(index + url.Length + 1);
        //            }
        //        }
        //        PaserFace(text);

        //    }
        //    catch(Exception ex)
        //    {
                
        //    }
        //}

        /// <summary>
        /// 设置内容解析帐号
        /// </summary>
        //public void SetContent(string text,ICollection<SDK.Objects.UserInfo> userInfos) {
        //    this.Blocks.Clear();
        //    PaserContent(userInfos,text);
        //}


        /// <summary>
        /// 设置内容解析帐号
        /// </summary>
        public void SetContent(string text)
        {
            this.Blocks.Clear();
            PaserContent(Dal.User.Instance.GetUserDictionary(), text);
        }


        private void PaserContent(Dictionary<string, string> userInfos, string content)
        {

            const string reg = @"@([A-Za-z0-9-_]*)?|\#([^\#|.]+)\#|http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?|/(no|ok|乒乓|亲亲|便便|偷笑|傲慢|再见|冷汗|凋谢|刀|勾引|发呆|发怒|发抖|可怜|可爱|右哼哼|右太极|吐|吓|咒骂|咖啡|哈欠|啤酒|嘘|回头|困|坏笑|大兵|大哭|太阳|奋斗|委屈|害羞|尴尬|左哼哼|左太极|差劲|弱|强|得意|微笑|心碎|快哭了|怄火|惊恐|惊讶|憨笑|抓狂|折磨|抠鼻|抱拳|拥抱|拳头|挥手|握手|撇嘴|擦汗|敲打|晕|月亮|流汗|流泪|激动|炸弹|爱你|爱心|爱情|猪头|献吻|玫瑰|瓢虫|疑问|白眼|睡|磕头|示爱|礼物|篮球|糗大了|胜利|色|菜刀|蛋糕|街舞|衰|西瓜|调皮|足球|跳绳|跳跳|转圈|鄙视|酷|闪电|闭嘴|阴险|难过|飞吻|饥饿|饭|骷髅|鼓掌|呲牙)";
            var regAccount = new Regex(reg);
            var matches = regAccount.Matches(content);
            int lastPos = 0;
            Paragraph block = new Paragraph();
            foreach (Match match in matches)
            {
                if (match.Index != lastPos)
                {
                    block.Inlines.Add(TextRun(content.Substring(lastPos, match.Index - lastPos)));
                }
                var val = match.Value;
                if (!string.IsNullOrWhiteSpace(val))
                {
                    if (val.IndexOf("@", System.StringComparison.Ordinal) == 0) {
                        var run = new Run { Foreground = (SolidColorBrush)App.Current.Resources["DetailComponentBrush"], Text = GetUserNickName(val.Substring(1), userInfos) };
                        block.Inlines.Add(run);
                    }
                    else if (val.IndexOf("#", System.StringComparison.Ordinal) == 0)
                    {
                        var run = new Run { Foreground = (SolidColorBrush)App.Current.Resources["DetailComponentBrush"], Text = val };
                        block.Inlines.Add(run);
                    }
                    else if (val.IndexOf("/", System.StringComparison.Ordinal) == 0) {
                        var img = BindFaceImage(val.Substring(1));
                        if (img != null)
                        {
                            block.Inlines.Add(img);
                        }
                        else {
                            block.Inlines.Add(val);
                        }
                    }
                    else
                    {
                        var link = new Hyperlink
                        {
                            Foreground = (SolidColorBrush)App.Current.Resources["DetailComponentBrush"],
                            NavigateUri = new Uri(val, UriKind.Absolute)
                        };
                        link.Inlines.Add(val);
                        link.Click += HyperlinkClick;
                        block.Inlines.Add(link);
                    }
                    
                    lastPos = match.Index + match.Length;
                }
            }
            if (lastPos < content.Length)
            {
                block.Inlines.Add(TextRun(content.Substring(lastPos)));
            }
            this.Selection.Insert(block);
        }



        private Run TextRun(string text) { 
            return new Run {
                Foreground = new SolidColorBrush((Color)App.Current.Resources["DetailContentColor"]), 
                Text =text,
                FontFamily=new FontFamily("Microsoft YaHei")
            };

        }

        private static string GetUserNickName(string name, Dictionary<string, string> users)
        {
            var rs = name;
            //if (users != null)
            //{
            //    foreach (var u in users)
            //    {
            //        if (string.Compare(name, u.Name, StringComparison.CurrentCultureIgnoreCase) == 0)
            //        {
            //            return u.NickName;
            //        }
            //    }
            //}
            if(users.ContainsKey(name))
            {
                return users[rs];
            }
            return "@"+rs;
        }



        ///// <summary>
        ///// 转换文本中的表情
        ///// </summary>
        ///// <param name="text"></param>
        //private void PaserFace(string text)
        //{
        //    if (string.IsNullOrEmpty(text)) return;
        //    var blocks = text.Split('/');
        //    for (int j = 0; j < blocks.Length; j++)
        //    {
        //        var tmp = blocks[j];
        //        if (tmp.Length > 0)
        //        {
        //            if (tmp.Length >= 1 && Helper.FaceHelper.Exist(tmp.Substring(0, 1)))
        //            {
        //                var faceName = tmp.Substring(0, 1);
        //                var face = BindFaceImage(faceName);
        //                this.Selection.Insert(face);
        //                this.Selection.Insert(new Run { Text = tmp.Substring(1) });
        //            }
        //            else if (tmp.Length >= 2 && Helper.FaceHelper.Exist(tmp.Substring(0, 2)))
        //            {
        //                var faceName = tmp.Substring(0, 2);
        //                var face = BindFaceImage(faceName);
        //                this.Selection.Insert(face);
        //                this.Selection.Insert(new Run { Text = tmp.Substring(2) });
        //            }
        //            else
        //            {
        //                this.Selection.Insert(new Run { Text = tmp });
        //            }
        //        }
        //        else
        //        {
        //            this.Selection.Insert(new Run { Text = tmp });
        //        }
        //    }
        //}

        /// <summary>
        /// 生成表情图片
        /// </summary>
        /// <param name="faceName"></param>
        /// <returns></returns>
        private InlineUIContainer BindFaceImage(string faceName)
        {

            if (Helper.FaceHelper.Exist(faceName)) 
            {
                var uri = new Uri(Helper.FaceHelper.GetFaceUrlFromChinese(faceName), UriKind.Relative);
                var face = new Image
                {
                    Source = new System.Windows.Media.Imaging.BitmapImage(uri),
                    Stretch = Stretch.Fill,
                    Width = 27,
                    Height = 27,
                    Margin = new Thickness(0, 0, 0, 0)
                };
                var uiContainer = new InlineUIContainer();
                uiContainer.Child = face;
                return uiContainer;
            }
            return null;
        }
        /// <summary>
        /// 打开网页
        /// </summary>
        private void HyperlinkClick(object sender, RoutedEventArgs e)
        {
            try
            {
                Dispatcher.BeginInvoke(() =>
                {
                    var link = sender as Hyperlink;
                    var webBrowserTask = new WebBrowserTask
                    {
                        Uri = new Uri(link.NavigateUri.AbsoluteUri, UriKind.Absolute)
                    };
                    webBrowserTask.Show();
                });
            }
            catch
            {

            }
        }
    }
}
